package admin

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"strings"
)

type Region struct {
	Ctx iris.Context
}

type CreateRegion struct {
	Id         string `json:"id"`
	ProvinceId int64  `json:"provinceId"`
	CityId     int64  `json:"cityId"`
	Name       string `json:"name"`
	Code       string `json:"code"`
	Level      int    `json:"level"`
}

type RegionListParam struct {
	ParentId int `json:"parentId"`
}

type GetChildrenParam struct {
	ParentId int `json:"parentId"`
	Level    int `json:"level"`
}

func (c *Region) OptionsChildren() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *Region) PostChildren() interface{} {
	getChildrenParam := GetChildrenParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接受请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &getChildrenParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("参数解析出错：%s", err.Error()), "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	regionList := make([]models.Region, 0)
	err = db.Where("parent_id = ?", getChildrenParam.ParentId).Find(&regionList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("获取区域列表失败：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "成功获取区域列表", regionList)
}

func (c *Region) OptionsCreate() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *Region) PostCreate() interface{} {
	createRegion := CreateRegion{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接受请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &createRegion)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("参数解析出错:%s", err.Error()), "")
	}

	if len(createRegion.Name) <= 0 {
		return utils.CommonRes(1000, "请输入区域名称", "")
	}

	parentId := int64(0)
	level := 1
	if createRegion.ProvinceId > 0 && createRegion.CityId <= 0 {
		parentId = createRegion.ProvinceId
		level = 2
	} else if createRegion.CityId > 0 {
		parentId = createRegion.CityId
		level = 3
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("数据库连接出错：%s", err.Error()), "")
	}

	region := new(models.Region)
	region.ParentId = parentId
	region.Name = createRegion.Name
	region.Code = createRegion.Code
	region.Level = level
	_, err = db.InsertOne(region)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("操作失败：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "操作成功", "")
}

func (c *Region) OptionsEdit() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *Region) PostEdit() interface{} {
	createRegion := CreateRegion{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接受请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &createRegion)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("参数解析出错：%s", err.Error()), "")
	}

	if len(createRegion.Id) <= 0 {
		return utils.CommonRes(1000, "请提供区域id", "")
	}
	if len(createRegion.Name) <= 0 {
		return utils.CommonRes(1000, "请输入区域名称", "")
	}

	parentId := int64(0)
	level := 1
	if createRegion.ProvinceId > 0 && createRegion.CityId <= 0 {
		parentId = createRegion.ProvinceId
		level = 2
	} else if createRegion.CityId > 0 {
		parentId = createRegion.CityId
		level = 3
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("数据库连接出错：%s", err.Error()), "")
	}

	data := map[string]interface{}{
		"parent_id": parentId,
		"name":      createRegion.Name,
		"code":      createRegion.Code,
		"level":     level,
	}
	_, err = db.Table(new(models.Region)).ID(createRegion.Id).Update(data)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("操作失败:%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "操作成功", "")
}

func (c *Region) OptionsList() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *Region) PostList() interface{} {
	regionListParam := RegionListParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接受请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &regionListParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("参数解析出错：%s", err.Error()), "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	regionList := make([]models.Region, 0)
	err = db.Where("parent_id = ?", regionListParam.ParentId).Find(&regionList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("获取区域列表失败：%s", err.Error()), "")
	}

	for i, item := range regionList {
		has, err := db.Where("parent_id = ?", item.Id).Exist(new(models.Region))
		if err == nil && has {
			regionList[i].HasChildren = true
		} else {
			regionList[i].HasChildren = false
		}
	}

	return utils.CommonRes(20000, "成功获取区域列表", regionList)
}

func (c *Region) OptionsDetail() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *Region) PostDetail() interface{} {
	editParam := utils.EditParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &editParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	if len(editParam.Id) <= 0 {
		return utils.CommonRes(1000, "参数不完整", "")
	}
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	region := new(models.Region)
	ok, err := db.ID(editParam.Id).Get(region)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("信息获取失败:%s", err.Error()), "")
	}
	if !ok {
		return utils.CommonRes(1000, "信息获取失败", "")
	}

	if region.Level == 3 {
		city := new(models.Region)
		ok, err := db.ID(region.ParentId).Get(city)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("信息获取失败:%s", err.Error()), "")
		}
		if !ok {
			return utils.CommonRes(1000, "信息获取失败", "")
		}
		region.ProvinceId = city.ParentId
	}

	return utils.CommonRes(20000, "信息获取成功", region)
}

func (c *Region) OptionsDel() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *Region) PostDel() interface{} {
	delParam := utils.DelParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接受请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &delParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("参数解析出错：%s", err.Error()), "")
	}

	if len(delParam.Ids) <= 0 {
		return utils.CommonRes(1000, "请提供要删除项的id", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	ids := strings.Split(delParam.Ids, ",")
	for _, id := range ids {
		region := new(models.Region)
		db.ID(id).Get(region)
		db.ID(id).Delete(region)
	}

	return utils.CommonRes(20000, "操作成功", "")
}
